Class & Object

  • Note

    1. What is a class

    A class help us to bind the data and methods together, making the code reusable.

    Class is the blueprint or user-defined layout of an object. Class contains properies and behaviours of an object. A class can't be used directly in the programming. So we need to create an object from the class

    2. What is an object

    An object is a variable. We can store multiple values and functions in an object. An object could not be created like a normal variable. An object is created from a class. So a class is mandatory for the object.

    3. Advantages

    1. Encapsulation : a) It provides you the control over the data. b) data hiding

    2. Inheritance : a) Avoid the duplication of code

    3. Modularity : reduce the complexity of the project by dividing the project into small classes

    4. Ease of code maintance

    System allocates memory for every data member in the class when an object of a class is instantiated.

  • Create a class & object

    Create Class

    Create a class using the keyword 'class'

    Syntax
    
                       class ClassName
                       {
    
                                   //...
                      
                       }
    
                      
    eg1:
    
                       class Student
                       {
    
                                   //...
                      
                       }
    
                       
    eg2:
    
                       class Teacher
                       {
    
                                   //...
                      
                       }
                       

    Add the properties and methods to a class

    
                       class Student
                       {
    
                               $name;
                               $marks;
                               $income;
    
                               function findGrade(){
    
                               }
    
                               function findFee(){
                                  
                              }
                      
                       }
    
                       

    Set or get value to class properties

    1. Create an object of a class using the keyword 'new'

    2. Assign the object to a variable

    Syntax
    
                       $objectName= new ClassName();
                      
    eg1:
    
                       $student= new Student();
                      

    3. set the value with '->' operator

    
                      $student->name = "manoj";
                      

    4. get the value with '->' operator

    
                      $student->name;
                      

    5. call the function with '->' operator

    
                      $student->findGrade();